import 'package:FlutterStudy/demo/TextFieldDemo.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';


class FormDemo extends StatelessWidget {
  final formKey = GlobalKey<FormState>();
  String? userName;
  String? paswword;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Theme.of(context).primaryColor,
      padding: EdgeInsets.all(10),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(
            child: TextFieldDemo(),
            height: 100,
            width: MediaQuery.of(context).size.width - 20,
          ),
          Form(
            key: formKey,
            child: Column(
              children: [
                TextFormField(
                  decoration: InputDecoration(
                    labelText: "useName",
                    floatingLabelStyle: TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                    ),
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                  ),
                  onSaved: (txt) => userName = txt,
                ),
                TextFormField(
                  obscureText: true,
                  autovalidateMode: AutovalidateMode.always,
                  onSaved: (txt) => paswword = txt,
                  validator: validatorPassword,
                  decoration: InputDecoration(

                    labelText: "password",
                    floatingLabelStyle: TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                    ),
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                  ),
                ),
                Container(
                  width: double.infinity,
                  child: MaterialButton(
                    onPressed: () {
                      if(formKey.currentState!.validate()){
                        formKey.currentState?.save();

                        debugPrint('用户名字 ${userName} \n 密码 ${paswword}');
                      }else{
                        
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text('验证失败，请检查输入内容')),
                        );
                      }

                    },
                    color: Colors.pink,
                    child: Text("提交"),
                  ),
                ),
              ],
            ),
          ),

          // TextFieldDemo(),
        ],
      ),
    );
  }

  String? validatorPassword(String? value) {
    if (value == null || value.isEmpty) return 'password is required';
    if (value.length < 6) return '密码至少要6位数以上';
    return null;
  }
}
